package org.example;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class StreamWordCount {
    public static void main(String[] args) throws Exception {
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // iEDEA运行时。也可以看到webui，一般用于本地测试
        Configuration configuration = new Configuration();
        configuration.setString("rest.port", "8088");
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment(configuration);

        env.setParallelism(3);

//        DataStreamSource<String> localhost = env.socketTextStream("192.168.0.175", 8777);
        DataStreamSource<String> localhost = env.socketTextStream("hadoop102", 8777);

        ParameterTool parameterTool = ParameterTool.fromArgs(args);

        // 讲每一行数据拆分
        SingleOutputStreamOperator<Tuple2<String, Long>> flatMapOperator = localhost.flatMap((String line, Collector<Tuple2<String, Long>> out) -> {
            String[] words = line.split(" ");
            for (String s : words) {
                out.collect(Tuple2.of(s, 1L));
            }
        })/*.setParallelism(2)*/
                .returns(Types.TUPLE(Types.STRING, Types.LONG));

        // 按照word进行分组
        KeyedStream<Tuple2<String, Long>, String> keyBy = flatMapOperator.keyBy(value -> {
            return value.f0;
        });

        // 分组内进行聚合统计
        SingleOutputStreamOperator<Tuple2<String, Long>> sum = keyBy.sum(1);
        sum.print();

        env.execute();
    }
}

